package com.mbc.web.common.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;
import com.mbc.web.common.shared.HttpStatus;
import com.mbc.common.entities.Branch;
import com.mbc.common.entities.BranchType;
import com.mbc.common.entities.Country;
import com.mbc.web.common.client.ButtonActionType;
import com.mbc.web.common.client.ClientSingleton;
import com.mbc.web.common.client.CommonControllerMgr;
import com.mbc.web.common.client.CommonMessage;
import com.mbc.web.common.client.ViewUtils;
import com.mbc.web.common.client.ui.control.MButton;
import com.mbc.web.common.client.ui.control.MListBox;
import com.mbc.web.common.client.ui.control.MTextBox;
import com.mbc.web.common.shared.dto.BranchViewLoadDTO;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;

public class FrmBranch extends Composite {

	@UiField MButton btnSave;
	@UiField MButton btnEdit;
	@UiField MButton btnDelete;
	@UiField MButton btnReset;
	@UiField MButton btnNew;
	@UiField MButton btnList;
	@UiField MButton btnBack;
	@UiField MTextBox txtBranchCode;
	@UiField MTextBox txtName;
	@UiField MTextBox txtCity;
	@UiField MListBox listCountry;
	@UiField MListBox listBranchType;
	@UiField MTextBox txtPhone;
	@UiField MTextBox txtFax;
	@UiField MTextBox txtEmail;
	@UiField MTextBox txtAddress;
	
	private long branchId;;
	private Branch branch;
	private byte action_type;
	
	private static FrmBranchUiBinder uiBinder = GWT
			.create(FrmBranchUiBinder.class);

	interface FrmBranchUiBinder extends UiBinder<Widget, FrmBranch> {
	}

	public FrmBranch() {
		initWidget(uiBinder.createAndBindUi(this));
		initialize();
		onBtnNewClick(null);
	}

	public FrmBranch(Branch branch){
		initWidget(uiBinder.createAndBindUi(this));
		initialize();
		this.branch = branch;
		enableControls(false);
		btnSave.setEnabled(false);
		btnEdit.setEnabled(true);
		btnDelete.setEnabled(true);
		btnReset.setEnabled(false);
	}
	
	private void initialize(){
		
		txtBranchCode.getElement().setAttribute("style", "text-transform: uppercase;");
		
		Scheduler.get().scheduleDeferred(new ScheduledCommand() {
			
			@Override
			public void execute() {
				txtBranchCode.setFocus(true);
			}
		});
		
		CommonControllerMgr.getBranchViewLoadDTO(getBranchViewLoadDTOCallback());
	}
	
	private AsyncCallback<BranchViewLoadDTO> getBranchViewLoadDTOCallback(){
		return new AsyncCallback<BranchViewLoadDTO>() {
			
			@Override
			public void onSuccess(BranchViewLoadDTO result) {
				if(result.getHttpStatus() == HttpStatus.OK){
					for (BranchType l_BranchType : result.getBranchTypeList()) {
						listBranchType.addItem(l_BranchType.getName(), String.valueOf(l_BranchType.getBranchTypeId()));
					}
					for (Country l_Country : result.getCountryList()) {
						listCountry.addItem(l_Country.getName(), l_Country.getCountryCode());
					}
				}
				
				if(branch != null){
					bindControls(branch);
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		};
	}
	
	private void enableControls(boolean enabled){
		txtBranchCode.setEnabled(enabled);
		txtName.setEnabled(enabled);
		txtCity.setEnabled(enabled);
		listCountry.setEnabled(enabled);
		listBranchType.setEnabled(enabled);
		txtPhone.setEnabled(enabled);
		txtFax.setEnabled(enabled);;
		txtEmail.setEnabled(enabled);
		txtAddress.setEnabled(enabled);
	}
	
	private native void jsClear()/*-{
		$wnd.$("input").val("");
		$wnd.$("select").prop("selectedIndex","0");
	}-*/;
	
	private void  clear(){
		jsClear();
		ViewUtils.clearRequiredNotifications();
		branchId = 0;
		branch = null;
	}
	
	private void bindControls(Branch branch){
		txtBranchCode.setText(branch.getBranchCode());
		txtCity.setText(branch.getCity());
		txtName.setText(branch.getName());
		for (int i = 0; i < listBranchType.getItemCount(); i++) {
			if(listBranchType.getValue(i).equals(String.valueOf(branch.getBranchTypeId()))){
				listBranchType.setSelectedIndex(i);
				break;
			}
		}
		for (int i = 0; i < listCountry.getItemCount(); i++) {
			if(listCountry.getValue(i).equals(branch.getCountry())){
				listCountry.setSelectedIndex(i);
				break;
			}
		}
		txtAddress.setText(branch.getAddress());
		txtEmail.setText(branch.getEmail());
		txtFax.setText(branch.getFax());
		txtPhone.setText(branch.getPhone());
		branchId = branch.getBranchId();
	}
	
	private Branch bindBranch(){
		Branch l_Branch = new Branch();
		l_Branch.setBranchId(branchId);
		l_Branch.setBranchCode(txtBranchCode.getText());
		l_Branch.setCity(txtCity.getText());
		l_Branch.setName(txtName.getText());
		l_Branch.setCountry(listCountry.getValue(listCountry.getSelectedIndex()));
		l_Branch.setBranchTypeId(Long.parseLong(listBranchType.getValue(listBranchType.getSelectedIndex())));
		l_Branch.setFax(txtFax.getText());
		l_Branch.setEmail(txtEmail.getText());
		l_Branch.setPhone(txtPhone.getText());
		l_Branch.setAddress(txtAddress.getText());
		return l_Branch;
	}
	
	private AsyncCallback<Integer> actionCallback()
	{
		return new AsyncCallback<Integer>() {
			
			@Override
			public void onSuccess(Integer result) {
				ViewUtils.stopAjaxLoader();
				if(result == HttpStatus.OK){
					switch (action_type) {
					case ButtonActionType.action_save:
						ViewUtils.showSuccessMessage(CommonMessage.saved_message);
						ClientSingleton.changeView(new SearchBranch(txtBranchCode.getText(), SearchBranch.SAVE));
						break;
					case ButtonActionType.action_delete:
						ViewUtils.showSuccessMessage(CommonMessage.deleted_message);
						ClientSingleton.changeView(new SearchBranch(txtBranchCode.getText(), SearchBranch.DELETE));
						break;
					}
				}
				else{
					switch (result) {
					case HttpStatus.INTERNAL_SERVER_ERROR:
						ViewUtils.showErrorMessage(CommonMessage.internal_server_error_message);
						break;
					case HttpStatus.BAD_REQUEST:
						ViewUtils.showErrorMessage(CommonMessage.getAlreadyExistedMessage("Branch Code(" + txtBranchCode.getText() + ")"));
						break;
					case HttpStatus.FORBIDDEN:
						ViewUtils.showErrorMessage(CommonMessage.getDataCannotDeleteMessage("Branch Code(" + txtBranchCode.getText() + ")"));
						break;
					}
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		};
	}
	
	@UiHandler("btnNew")
	void onBtnNewClick(ClickEvent event) {
		clear();
		enableControls(true);
		txtBranchCode.setFocus(true);
		btnSave.setEnabled(true);
		btnEdit.setEnabled(false);
		btnDelete.setEnabled(false);
		btnReset.setEnabled(false);
	}
	
	@UiHandler("btnSave")
	void onBtnSaveClick(ClickEvent event) {
		if(ViewUtils.isValidate()){
			action_type = ButtonActionType.action_save;
			ViewUtils.startAjaxLoader(CommonMessage.loading_message);
			if(branchId == 0)
				CommonControllerMgr.createBranch(bindBranch(), actionCallback());
			else
				CommonControllerMgr.updateBranch(bindBranch(), actionCallback());
		}
	}
	
	@UiHandler("btnEdit")
	void onBtnEditClick(ClickEvent event) {
		if(branchId != 0)
		{
			btnReset.setEnabled(true);
			btnSave.setEnabled(true);
			btnEdit.setEnabled(false);
			btnNew.setEnabled(false);
			enableControls(true);
			txtName.setFocus(true);
			txtBranchCode.setEnabled(false);
		}
	}
	
	@UiHandler("btnDelete")
	void onBtnDeleteClick(ClickEvent event) {
		if(branchId != 0)
		{
			ViewUtils.showConfirm(CommonMessage.delete_confirm_message, new CloseHandler<PopupPanel>() {
				
				@Override
				public void onClose(CloseEvent<PopupPanel> event) {
					if(ViewUtils.isAlertYes()){
						action_type = ButtonActionType.action_delete;
						ViewUtils.startAjaxLoader(CommonMessage.deleting_message);
						CommonControllerMgr.deleteBranch(branchId, actionCallback());
					}
				}
			});
		}
	}
	
	@UiHandler("btnReset")
	void onBtnResetClick(ClickEvent event) {
		bindControls(branch);
		enableControls(false);
		btnReset.setEnabled(false);
		btnSave.setEnabled(false);
		btnEdit.setEnabled(true);
		btnNew.setEnabled(true);
	}
	
	@UiHandler("btnBack")
	void onBtnBackClick(ClickEvent event) {
		ClientSingleton.changeView(new SearchBranch());
	}
	
	@UiHandler("btnList")
	void onBtnListClick(ClickEvent event) {
		ClientSingleton.changeView(new FrmBranchRpt());
	}
	
	
}
